<template>
  <div class="app-container">
    <el-form :model="form" ref="formRef" :scroll-to-error="true" v-loading="formLoading">
      <el-space direction="vertical">
        <div shadow="never" class="assess">
          <el-row justify="center" class="task-title assess-title">
            <el-form-item label="当前任务编号：" prop="assessCode">
              <span>{{ form.assessCode }}</span>
            </el-form-item>
            <el-form-item label="当前任务名称：" prop="assessName">
              <span>{{ form.assessName }}</span>
            </el-form-item>
          </el-row>
          <el-row justify="center" class="assess-title">
            <el-form-item label="评估区域：" prop="list">
              {{ form.list?.map(item => {
                  let area = []
                  item.ppName && area.push(item.ppName)
                  item.cityName && area.push(item.cityName)
                  item.name && area.push(item.name)
                  return area
                }).map(item => item.join('-')).join('、')
              }}
            </el-form-item>
            <el-form-item label="房屋基础数据：" prop="houseDataFlag">
              {{ houseBasicData.find(item => item.value == form.houseDataFlag)?.name }}
            </el-form-item>
            <el-form-item label="地震输入方式：" prop="seismicInputMode">
              <span>
                {{ inputMode?.map(item => seismicInputMode.find(cur => cur.value == item)?.name).join('、') }}
              </span>
            </el-form-item>
          </el-row>
        </div>
      </el-space>
      <template v-if="isCurTask">
        <el-space direction="vertical" v-if="props.type == TYPE.confirm">
          <div shadow="never" class="assess">
            <el-row>
              <el-radio-group v-model="form.seismicInputMode" class="column" @change="seismicInputModeChange">
                <el-radio v-for="item in inputMethods(type)" :key="item.value" :label="item.value" size="large"
                  v-show="inputMode?.includes(item.value)">
                  {{ item.name }}
                  <span v-if="item.value == '0'">（选择烈度计算时，计算结果包含每个烈度下五个破坏状态下的计算值，共25组值）</span>
                  <span v-if="item.value == '1'">（选择超越概率计算时，计算结果包含每个概率水准下五个破坏状态下的计算值，共20组值）</span>
                  <span v-if="item.value == '2'">（选择地震影响场计算时，计算结果包含五个破坏状态下的计算值，共5组值）</span>
                </el-radio>
              </el-radio-group>
            </el-row>
          </div>
        </el-space>
        <el-row style="margin: 10px 0;">
          <el-button plain @click="calculationFunc">评估</el-button>
          <el-button plain @click="importExcel">导入</el-button>
        </el-row>
        <el-space direction="vertical">
          <div shadow="never" class="assess">
            <el-row>
              <el-form-item prop="seismicInputMode1">
                <el-radio-group v-model="form.seismicInputMode1" @change="seismicInputMode1Change">
                  <!-- <el-radio v-for="item in curInputMethods" :key="item.value" :label="item.value" size="large"> -->
                  <el-radio v-for="item in inputMethods(type)" :key="item.value" :label="item.value" size="large"
                    v-show="inputMode?.includes(item.value)">
                    {{ item.name }}
                    <el-select v-model="form.condition0" v-show="form.seismicInputMode1 == '0' && item.value == '0'">
                      <el-option v-for="item in dictData.intensity" :key="item.dictItemId" :label="item.dictItemName"
                        :value="item.dictItemCode" />
                    </el-select>
                    <el-select v-model="form.condition1" v-show="form.seismicInputMode1 == '1' && item.value == '1'">
                      <el-option v-for="item in dictData.probability" :key="item.dictItemId" :label="item.dictItemName"
                        :value="item.dictItemCode" />
                    </el-select>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-row>
            <!-- <el-form-item label="T年" label-width="90px" prop="years" v-if="props.type == TYPE.probability">
              <el-select v-model="form.years">
                <el-option v-for="item in form.year.split(',')" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item> -->
            <!-- <el-option v-for="item in dictData.years" :key="item.dictItemName" :label="item.dictItemName"
                  :value="item.dictItemName.slice(0, item.dictItemName.length - 1)"
                  v-if="[URL.casualtiesPE, URL.EconomicLossPD].includes(url)" />
                <el-option v-for="item in dictData.years" :key="item.dictItemId" :label="item.dictItemName"
                  :value="item.dictItemName.slice(0, item.dictItemName.length - 1)" v-else /> -->
            <!-- <el-form-item label="T年" label-width="90px" prop="years" v-if="props.type == TYPE.probability">
              <span style="color: var(--el-input-text-color, var(--el-text-color-regular))">{{ form.years }}年</span>
            </el-form-item> -->
            <el-space v-if="[URL.resistEarthquakesDE, URL.resistEarthquakesPE].includes(props.url)">
              <el-form-item label="破坏程度" label-width="90px">
                <el-select v-model="form.damageDegree">
                  <el-option v-for="item in dictData.damage" :key="item.dictItemId" :label="item.dictItemName"
                    :value="item.dictItemCode" />
                </el-select>
              </el-form-item>
            </el-space>
            <el-space v-if="[URL.casualtiesDE, URL.casualtiesPE].includes(props.url)" alignment="flex-start">
              <el-form-item label="人员伤亡" label-width="90px">
                <el-select v-model="form.casualties">
                  <el-option v-for="item in dictData.casualties" :key="item.dictItemId" :label="item.dictItemName"
                    :value="item.dictItemCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="时间段" label-width="90px">
                <el-select v-model="form.time">
                  <el-option v-for="item in dictData.time" :key="item.dictItemId" :label="item.dictItemName"
                    :value="item.dictItemCode" />
                </el-select>
              </el-form-item>
            </el-space>
          </div>
        </el-space>
        <el-row style="margin: 10px 0" v-show="!evaluateResultMap">
          <el-button type="primary" @click="viewTable" v-if="isShow">查询</el-button>
          <el-button type="primary" @click="exportTable" :disabled="dataList.length == 0" v-if="isShow">导出</el-button>
          <el-button type="primary" @click="showEvaluateResult" v-if="!isShow">查看计算结果</el-button>
          <el-button type="primary" @click="showEvaluateRegion" v-if="!(url=='resistEarthquakesDE'||url=='resistEarthquakesPE')">查看区域统计结果</el-button>
          <el-button type="primary" @click="showEvaluateResultMap">查看评估图</el-button>
        </el-row>
        <el-row style="margin: 10px 0" v-show="evaluateResultMap">
          <el-button type="primary" @click="showEvaluateResult">查看计算结果</el-button>
          <el-button type="primary" @click="showEvaluateRegion" v-if="!(url=='resistEarthquakesDE'||url=='resistEarthquakesPE')">查看区域统计结果</el-button>
          <el-button type="primary" @click="showEvaluateResultMap">查看评估图</el-button>
        </el-row>
        <div v-show="!evaluateResultMap">
          <!-- 确定评估表格 -->
          <ConfirmTable :dataList="dataList" :url="url" :isShow="isShow" :form="form" :loading="loading"
            v-if="TYPE.confirm == props.type" @viewTable="viewTable" />
          <!-- 概率评估表格 -->
          <ProbabilityTable :dataList="dataList" :url="url" :isShow="isShow" :form="form" :loading="loading"
            v-if="TYPE.probability == props.type" @viewTable="viewTable" />

          <pagination style="margin-top: 15px" v-show="queryParams.total > 0" :total="queryParams.total"
            v-model:page="queryParams.page" v-model:limit="queryParams.rows" @pagination="viewTable" v-if="isShow"/>
        </div>
        <div v-if="evaluateResultMap">
          <ConfirmSeismicMap :params="mapParams" v-if="url == URL.resistEarthquakesDE" />
          <ConfirmCasualtiesMap :params="mapParams" v-if="url == URL.casualtiesDE" />
          <ConfirmEconomicLossMap :params="mapParams" v-if="url == URL.EconomicLossED" />
          <ProbabilitySeismicMap :params="mapParams" v-if="url == URL.resistEarthquakesPE" />
          <ProbabilityCasualtiesMap :params="mapParams" v-if="url == URL.casualtiesPE" />
          <ProbabilityEconomicLossMap :params="mapParams" v-if="url == URL.EconomicLossPD" />
        </div>
      </template>
      <template v-else>
        <Empty :description="`无${route.meta.title}评估`" />
      </template>
    </el-form>
    <!-- 导入 -->
    <ExcelImport v-model:open="importOpen" :uploadParams="uploadParams" @importSuccess="importSuccess" />
  </div>
</template>

<script setup>
import { getTasks, calculation, queryCalculation ,statistics} from '@/api/building/index'
import { CODE, TYPE, URL, inputMethods, houseBasicData, seismicInputMode, assessObj } from '@/views/building/index'
import { getDict } from '@/api/system/dict.js'
import { ElLoading, ElMessageBox } from 'element-plus'
import ExcelImport from '@/components/ExcelImport'
import ConfirmTable from '@/views/building/components/confirmTable.vue'
import ProbabilityTable from '@/views/building/components/probabilityTable.vue'
import ConfirmSeismicMap from '@/views/building/confirm/seismic/map/index.vue'
import ConfirmCasualtiesMap from '@/views/building/confirm/personCasualties/map/index.vue'
import ConfirmEconomicLossMap from '@/views/building/confirm/economicLosses/map/index.vue'
import ProbabilitySeismicMap from '@/views/building/probability/seismic/map/index.vue'
import ProbabilityCasualtiesMap from '@/views/building/probability/personCasualties/map/index.vue'
import ProbabilityEconomicLossMap from '@/views/building/probability/economicLosses/map/index.vue'

const props = defineProps({
  type: String,
  url: String
})
const route = useRoute()
const { proxy } = getCurrentInstance()

const form = ref({})
const formLoading = ref(false)
const isCurTask = computed(() => {
  let assessObjFlag = form.value.assessObj?.includes(assessObj.find(item => item.name == route.meta.title)?.value)
  // return true
  if (props.type == TYPE.confirm) {
    return assessObjFlag && form.value.assessType == '0'
  } else {
    return assessObjFlag && form.value.assessType == '1'
  }
})
let inputMode = ref()
// 当前任务信息
const getCurrentTask = () => {
  formLoading.value = true
  getTasks().then(res => {
    if (res.data && res.code == 200) {
      form.value = { ...form.value, ...res.data }
      inputMode.value = res.data.seismicInputMode.split(',')
      form.value.seismicInputMode = res.data.seismicInputMode.split(',').sort((a, b) => a - b)[0]
      form.value.seismicInputMode1 = res.data.seismicInputMode.split(',').sort((a, b) => a - b)[0]
      dictInit()
    }
    formLoading.value = false
  }).catch(() => { formLoading.value = false })
}
// 字典项
const dictData = ref({
  intensity: [],
  probability: [],
  damage: [],
  casualties: [],
  time: [],
  years: []
})
const dictInit = () => {
  if (inputMode.value.includes('0')) {
    getDictData('intensity', CODE.ld, 'condition0')
  }
  if (inputMode.value.includes('1')) {
    getDictData('probability', CODE.sgglsz, 'condition1')
  }
  if (props.url == URL.resistEarthquakesDE || props.url == URL.resistEarthquakesPE) {
    getDictData('damage', CODE.phcd, 'damageDegree')
  }
  if (props.url == URL.casualtiesDE || props.url == URL.casualtiesPE) {
    getDictData('casualties', CODE.rysw, 'casualties')
    getDictData('time', CODE.sjd, 'time')
  }
  if (props.url == URL.resistEarthquakesPE || props.url == URL.casualtiesPE || props.url == URL.EconomicLossPD) {
    // getDictData('years', CODE.tn, 'years')
    form.value.years = form.value.year.split(',')[0]
  }
}
const getDictData = (field, code, formField) => {
  getDict(code).then(res => {
    if(field == 'damage' && props.url == URL.resistEarthquakesPE){
      dictData.value[field] = res.data.filter((_,index) => index > 0)
    }else{
      dictData.value[field] = res.data
    }
    if (formField) {
      form.value[formField] = dictData.value[field][0].dictItemCode
      if (formField == 'years' && [URL.casualtiesPE, URL.EconomicLossPD].includes(props.url)) {
        form.value[formField] = dictData.value[field][0].dictItemName.slice(0, dictData.value[field][0].dictItemName.length - 1)
      }
    }
  })
}
// 计算
const calculationFunc = () => {
  const { id, seismicInputMode } = form.value
  const loading = ElLoading.service({
    lock: true,
    text: '计算中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  calculation(props.url, { taskId: id, seismicInputMode }).then(res => {
    loading.close()
    if (res.code == 200) {
      proxy.$modal.msgSuccess('计算成功')
    }else if(res.code == 405){
      ElMessageBox({title: '系统消息', message: res.message, confirmButtonText: '确定', type: 'warning' })
    }
  }).catch(() => { loading.close() })
}
// 导入
const importOpen = ref(false)
const uploadParams = ref({})
const importExcel = () => {
  importOpen.value = true
}
const templateName = ref()
const importType = ref()
watch(() => form.value.id, (newVal) => {
  const { id, assessCode, years } = form.value
  if (id) {
    templateName.value = getTemplateName()
    importType.value = getImportType()
    uploadParams.value = {
      url: `/${props.url}/importExcel`,
      templateName: templateName.value,
      templateUrl: '/template/download',
      config: true,
      params: { type: importType.value, id, code: assessCode, years },
      downloadParams: { fileName: templateName.value }
    }
  }
})
const getTemplateName = () => {
  const { radio2, seismicInputMode1 } = form.value
  let name = props.type === TYPE.confirm ? '建筑物确定评估' : '建筑物概率评估'
  let type = route.meta.title
  let areaName = radio2 == '0' ? '行政区划' : '地图圈选'
  let modeName = inputMethods(props.type).find(item => item.value == seismicInputMode1)?.name
  return `${name}-${type}-${areaName}-${modeName}.xlsx`
}
const getImportType = () => {
  const { radio2, seismicInputMode1 } = form.value
  let type
  if (radio2 == '0') {
    type = seismicInputMode1 == '0' ? '1' : '2'
  } else {
    type = seismicInputMode1 == '0' ? '3' : '4'
  }
  return type
}
const importSuccess = () => {
  viewTable()
}
const seismicInputModeChange = val => {
  form.value.seismicInputMode1 = val
}
const seismicInputMode1Change = () => {
  dataList.value = []
}
// 查询
const queryParams = ref({
  page: 1,
  rows: 10,
  total: 0
})
const loading = ref(false)
const dataList = ref([])
const viewTable = () => {
  dataList.value = []
  loading.value = true
  const { page, rows } = queryParams.value
  const { seismicInputMode1, id, casualties, time, damageDegree, years, influenceFieldVersion } = form.value
  let condition = seismicInputMode1 != '2' ? form.value[`condition${seismicInputMode1}`] : influenceFieldVersion
  let data
  if (props.url == URL.resistEarthquakesDE) {
    data = { seismicInputMode: seismicInputMode1, id, page, rows, condition, damageDegree }
  } else if (props.url == URL.casualtiesDE) {
    data = { seismicInputMode: seismicInputMode1, id, page, rows, condition, casualties, time }
  } else if (props.url == URL.EconomicLossED) {
    data = { seismicInputMode: seismicInputMode1, id, page, rows, condition }
  } else if (props.url == URL.resistEarthquakesPE) {
    data = { id, page, rows, damageDegree, years }
  } else if (props.url == URL.casualtiesPE) {
    data = { id, page, rows, casualties, time, years }
  } else if (props.url == URL.EconomicLossPD) {
    data = { id, page, rows, years }
  }
  queryCalculation(props.url, data).then(res => {
    if (res.code == 200 && res.data.rows) {
      loading.value = false
      dataList.value = res.data.rows
      queryParams.value.total = res.data.total
    }
  }).catch(() => loading.value = false)
}
const viewTable1 = () => {
  dataList.value = []
  loading.value = true
  const { page, rows } = queryParams.value
  const { seismicInputMode1, id, casualties, time, damageDegree, years, influenceFieldVersion } = form.value
  let condition = seismicInputMode1 != '2' ? form.value[`condition${seismicInputMode1}`] : influenceFieldVersion
  let data
  if (props.url == URL.resistEarthquakesDE) {
    data = { seismicInputMode: seismicInputMode1, id, page, rows, condition, damageDegree }
  } else if (props.url == URL.casualtiesDE) {
    data = { seismicInputMode: seismicInputMode1, id, page, rows, condition, casualties, time }
  } else if (props.url == URL.EconomicLossED) {
    data = { seismicInputMode: seismicInputMode1, id, page, rows, condition }
  } else if (props.url == URL.resistEarthquakesPE) {
    data = { id, page, rows, damageDegree, years }
  } else if (props.url == URL.casualtiesPE) {
    data = { id, page, rows, casualties, time, years }
  } else if (props.url == URL.EconomicLossPD) {
    data = { id, page, rows, years }
  }
  let taskId = form.value.id
  statistics(props.url, {...data,taskId}).then(res => {
    if (res.code == 200 && res.data) {
      loading.value = false
      dataList.value = res.data
      // queryParams.value.total = res.data.total
    }
  }).catch(() => loading.value = false)
}
// 导出数据
const exportTable = () => {
  const { seismicInputMode1, id, damageDegree, casualties, time, years, influenceFieldVersion } = form.value
  let condition = seismicInputMode1 != '2' ? form.value[`condition${seismicInputMode1}`] : influenceFieldVersion
  let params = { seismicInputMode: seismicInputMode1, id, condition }

  if (props.url == URL.resistEarthquakesDE) {
    params = { ...params, damageDegree }
  } else if (props.url == URL.casualtiesDE) {
    params = { ...params, casualties, time }
  } else if (props.url == URL.EconomicLossED) {
    params = { ...params }
  } else if (props.url == URL.resistEarthquakesPE) {
    params = { id, damageDegree, years }
  } else if (props.url == URL.casualtiesPE) {
    params = { id, casualties, time, years }
  } else if (props.url == URL.EconomicLossPD) {
    params = { id, years }
  }

  proxy.download(`/${props.url}/exportData`, params, `${templateName.value}`)
}
const evaluateResultMap = ref(false)
const mapParams = ref({})
// 查看计算结果
const showEvaluateResult = () => {
  isShow.value = true;
  evaluateResultMap.value = false
  viewTable()
}
// 查看评估区域
const isShow = ref(true)
const showEvaluateRegion = () =>{
  isShow.value = false;
  evaluateResultMap.value = false
  viewTable1()
}
// 查看评估图
const showEvaluateResultMap = () => {
  isShow.value = true;
  const { assessCode, seismicInputMode1, id, casualties, time, damageDegree, influenceFieldVersion, years } = form.value;
  let condition = seismicInputMode1 != '2' ? form.value[`condition${seismicInputMode1}`] : influenceFieldVersion
  if (props.url == "resistEarthquakesDE") {
    if (condition && damageDegree) {

    } else {
      proxy.$modal.msgWarning("请选择评估参数");
      return;
    }

    //结构破坏-确定评估地图查看结果
    mapParams.value = {
      type: "seismicEd",
      assessCode,
      seismicInputMode: seismicInputMode1,
      damageDegree,
      condition,
      coordinateRange: form.value.coordinateRange,
      influenceFieldVersion,
      id
    }
    evaluateResultMap.value = true
  } else if (props.url == "casualtiesDE") {
    if (condition && casualties && time) {

    } else {
      proxy.$modal.msgWarning("请选择评估参数");
      return;
    }
    let type = "personCasualtiesEd";
    if (time == "sjd1" && casualties == "rysw2") {//白天死亡
      type = "personCasualtiesEd_day_death";
    } else if (time == "sjd1" && casualties == "rysw1") {//白天重伤
      type = "personCasualtiesEd_day_injure";
    } else if (time == "sjd2" && casualties == "rysw2") {//夜间死亡
      type = "personCasualtiesEd_night_death";
    } else if (time == "sjd2" && casualties == "rysw1") {//夜间重伤
      type = "personCasualtiesEd_night_injure";
    } else {
      return;
    }
    //人员伤亡-确定评估地图查看结果
    mapParams.value = {
      type,
      assessCode,
      seismicInputMode: seismicInputMode1,
      casualties,
      time,
      coordinateRange: form.value.coordinateRange,
      condition,influenceFieldVersion,
      id
    }
    evaluateResultMap.value = true
  } else if (props.url == "EconomicLossED") {
    if (condition) {

    } else {
      proxy.$modal.msgWarning("请选择评估参数");
      return;
    }
    //经济损失-确定评估地图查看结果
    mapParams.value = {
      type: 'economicLossesEd',
      assessCode,
      seismicInputMode: seismicInputMode1,
      condition,influenceFieldVersion,
      coordinateRange: form.value.coordinateRange,
      id
    }
    evaluateResultMap.value = true
  } else if (props.url == "resistEarthquakesPE") {
    if (years && damageDegree) {

    } else {
      proxy.$modal.msgWarning("请选择评估参数");
      return;
    }
    //结构破坏-概率评估地图查看结果
    mapParams.value = {
      type: "seismicPd",
      assessCode,
      damageDegree,
      years,
      coordinateRange: form.value.coordinateRange,
      id
    }
    evaluateResultMap.value = true
  } else if (props.url == "casualtiesPE") {
    if (years && casualties && time) {

    } else {
      proxy.$modal.msgWarning("请选择评估参数");
      return;
    }
    //人员伤亡-概率评估地图查看结果
    mapParams.value = {
      type: 'personCasualtiesPd',
      assessCode,
      years,
      casualties,
      time,
      coordinateRange: form.value.coordinateRange,
      id
    }
    evaluateResultMap.value = true
  } else if (props.url == "EconomicLossPD") {
    if (years) {

    } else {
      proxy.$modal.msgWarning("请选择评估参数");
      return;
    }
    //经济损失-概率评估地图查看结果
    mapParams.value = {
      type: 'economicLossesPd',
      assessCode,
      years,
      coordinateRange: form.value.coordinateRange,
      id
    }
    evaluateResultMap.value = true
  }
}
onMounted(() => {
  getCurrentTask()
})
</script>
<style lang="scss" scoped>
.assess-dialog.el-dialog .el-dialog__body {
  padding: 20px 20px;
}

.el-form-item.el-form-item--default {
  margin: 10px 0;
}

.assess-title {
  .el-form-item.el-form-item--default {
    margin: 10px 20px;
  }
}
:deep(.el-space.el-space--vertical) {
  width: 100%;

  &>.el-space__item {
    width: 100%;
  }
}

.assess {
  border-radius: 4px;
  border: 1px solid #e4e7ed;

  .task-title {
    font-weight: bold;
    color: #606266;

    :deep(.el-form-item) {

      label,
      .el-form-item__content {
        font-size: 18px;
      }
    }
  }

  .border-bottom {
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-row {
    padding: 0 20px;
  }

  .title {
    font-weight: bold;
  }

  :deep(.column.el-radio-group) {
    flex-direction: column;
    align-items: start;

    &>.el-radio {
      &>.el-radio__label {
        &>.el-space {
          &>.el-space__item:first-of-type {
            margin-right: 50px !important;
          }
        }
      }
    }
  }
}
</style>